package com.library.uiframework.fragment;

import java.util.HashMap;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.ali.music.navigator.backstack.AbstractFragment;
import com.ali.music.navigator.backstack.FragmentBackStackManager;
import com.library.uiframework.mvp.IPageLifecycle;
import com.library.uiframework.mvp.PageLifecycleHelper;
import com.library.uiframework.utils.ContextUtils;
import com.library.uiframework.utils.SDKVersionUtils;

/**
 * BaseFragment.java
 * Created by james on 2015/9/25 09:54.
 * Copyright (c) 2015 james. All rights reserved.
 *
 * @author james.guo
 * @version 1.0.0
 */
public class BaseFragment extends AbstractFragment implements ILoadFinished {

    protected PageLifecycleHelper mPageLifecycleHelper = new PageLifecycleHelper();

    private HashMap<String, String> mProperties = new HashMap<String, String>();

    private enum LoadState {
        NONE,
        DOING_ANIM,
        WAITING_PARENT,
        FINISHED
    }

    private static final int ANIMATION_END_DELAY = 100; //ms
    private LoadState mLoadState = LoadState.NONE;

    private View mBusinessView;

    private static Drawable sGlobalBackgroundDrawable;

    /**
     * @return 全局背景图
     */
    public static Drawable getGlobalBackgroundDrawable() {
        return sGlobalBackgroundDrawable;
    }

    /**
     * 设置全局背景图,仅仅记录,新fragment打开的时候自动应用
     *
     * @param globalBackgroundDrawable 全局背景图
     */
    public static void setGlobalBackgroundDrawable(Drawable globalBackgroundDrawable) {
        sGlobalBackgroundDrawable = globalBackgroundDrawable;
    }

    final public void registerPageLifecycle(IPageLifecycle lifecycle) {
        mPageLifecycleHelper.register(lifecycle);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageLifecycleHelper = new PageLifecycleHelper();
    }

    @Override
    public void onDestroy() {
        getFragmentBackHelper().clearChildFragmentBackStackManager();
        super.onDestroy();
        mPageLifecycleHelper.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public <T extends View> T findViewById(int id) {
        return (T) getView().findViewById(id);
    }

    @Override
    public void onDetach() {
        setViewBackgroundDrawable(mBusinessView != null ? mBusinessView : getView(), null);
        super.onDetach();
        mBusinessView = null;
    }

    @Override
    public void onPause() {
        super.onPause();
        mPageLifecycleHelper.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mLoadState == LoadState.NONE && canLoadDataWhenResume()) {
            checkLoadFinished();
        }
        mPageLifecycleHelper.onResume();
    }

    @Override
    public void onNewPause() {
        super.onNewPause();
        mPageLifecycleHelper.onPause();
    }

    @Override
    public void onNewResume() {
        super.onNewResume();
        mPageLifecycleHelper.onResume();
    }

    @Override
    public void onStart() {
        super.onStart();
        mPageLifecycleHelper.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
        mPageLifecycleHelper.onStop();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (sGlobalBackgroundDrawable != null) {
            setBackgroundDrawable(sGlobalBackgroundDrawable);
        }

        registerPageLifecycles();
        mPageLifecycleHelper.onCreate();
    }

    protected void registerPageLifecycles() {
    }

    /**
     * 设置一个放业务主体内容的view,用来统一处理背景等
     *
     * @param businessView businessView
     */
    protected void setBusinessView(View businessView) {
        mBusinessView = businessView;
    }

    /**
     * 设置一个背景图,为节省内存,此图应该各UI页面共用
     *
     * @param drawable 背景大图
     */
    public void setBackgroundDrawable(Drawable drawable) {
        if (mBusinessView != null) {
            setViewBackgroundDrawable(mBusinessView, drawable);
        }
    }

    /**
     * 给某个view设置一个background
     *
     * @param view     view
     * @param drawable drawable
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setViewBackgroundDrawable(View view, Drawable drawable) {
        if (view != null) {
            if (SDKVersionUtils.hasJellyBean()) {
                view.setBackground(drawable);
            } else {
                view.setBackgroundDrawable(drawable);
            }
        }
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter) {
            try {
                if (nextAnim != 0) {

                    Animation anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);
                    anim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (mLoadState == LoadState.DOING_ANIM) {
                                        BaseFragment.this.checkLoadFinished();
                                    }
                                }
                            }, ANIMATION_END_DELAY);
                        }
                    });
                    mLoadState = LoadState.DOING_ANIM;
                    return anim;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        } else {
            onExitAnimationStart();
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public boolean isLoadFinished() {
        return mLoadState == LoadState.FINISHED;
    }

    @Override
    public void onLoadFinished() {

    }

    protected boolean canLoadDataWhenResume() {
        return true;
    }

    /**
     * 退出动画开始
     */
    protected void onExitAnimationStart() {

    }

    private void onParentFragmentLaunchFinished() {
        if (mLoadState == LoadState.WAITING_PARENT) {
            checkLoadFinished();
        }
    }

    protected void checkLoadFinished() {
        if (isResumed() && getUserVisibleHint()) {
            BaseFragment parentFragment = (BaseFragment) getParentFragment();
            if (parentFragment == null || parentFragment.isLoadFinished()) {
                if (getFragmentBackHelper().getParentFragmentBackStackManager() != null) {
                    getFragmentBackHelper().getParentFragmentBackStackManager().hidePreviousFragment(this);
                }
                mLoadState = LoadState.FINISHED;

                BaseFragment.this.onLoadFinished();

                List<Fragment> fragments = getChildFragmentManager().getFragments();
                if (fragments != null) {
                    for (Fragment fragment : fragments) {
                        if (fragment instanceof BaseFragment) {
                            ((BaseFragment) fragment).onParentFragmentLaunchFinished();
                        }
                    }
                }
            } else {
                mLoadState = LoadState.WAITING_PARENT;
            }
        }
    }

    public LayoutInflater requestLayoutInflater() {
        return getActivity().getLayoutInflater();
    }

    @Override
    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
        return getActivity().getLayoutInflater();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mLoadState == LoadState.NONE) {
            checkLoadFinished();
        }
    }

    /**
     * 隐藏软键盘
     */
    public void hideInputMethod() {
        Activity activity = getActivity();
        if (activity != null) {
            View focusView = activity.getCurrentFocus();
            if (focusView != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(focusView.getWindowToken(), 0);
            }
        }
    }

    public void hideInputMethod(EditText editText) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     *
     * @param editText 目标输入框
     */
    public void showInputMethod(EditText editText) {
        Activity activity = getActivity();
        if (activity != null && editText != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            editText.requestFocus();
            inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    }

    /**
     * 是否为TopFragment
     *
     * @return 是否为TopFragment
     */
    public boolean isTopFragment() {
        FragmentBackStackManager stackManager = getFragmentBackHelper().getParentFragmentBackStackManager();
        return null != stackManager && stackManager.getTopFragment() == this;
    }
}
